package com.ys.io.p4对象流;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 描述: p3使用对象流来序列化与反序列化对象
 * 该对象必须实现 Serializable 接口
 *
 * @author CodeYang
 * @version 2021/1/4 18:50
 */
public class p3使用对象流来序列化与反序列化对象 {

    public static void main(String[] args) {
        try {
            seriaObject();
            unseriaObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     */
    private static void unseriaObject() throws Exception {
        try (
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day_23/ysObject"))
        ) {
            OutObject object = (OutObject) ois.readObject();
            System.out.println("反序列化");
            System.out.println(object);
        }

    }

    /**
     * 序列化对象
     */
    private static void seriaObject() throws Exception {

        // 初始化对象
        OutObject outObject = new OutObject("ysObject", 18, new InnerObject("ws"));

        try (                // 序列化的磁盘路径是当前工程路径，序列化对象的文件名称就是学生的姓名
                             FileOutputStream fos = new FileOutputStream("day_23/" + outObject.getName());
                             ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            // 把对象序列化(持久到磁盘)

            oos.writeObject(outObject);
            System.out.println("序列化成功");


        }

    }
}
